﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using EquipmentConfig.Class;
using System.Threading;
using System.Diagnostics;

namespace EquipmentConfig
{
    public partial class HisDataDownLoad : Form
    {
        private MainForm mf;
        private DateTime dateStart;
        private DateTime dateEnd;
        private int dataCount;
        private int intReportingCycle;
        //private Thread sub;

        public HisDataDownLoad(MainForm mainForm, DateTime dtStart, DateTime dtEnd, int intTime ,int rowCount)
        {
            InitializeComponent();
            mf = mainForm;
            dateStart = dtStart;
            dateEnd = dtEnd;
            intReportingCycle = intTime;
            dataCount = rowCount;
            mf.timer2.Enabled = false;
            mf.recBuffer.Clear();
        }

        private void SendHisData(byte[] sendbyte)
        {
            for (int j = 0; j < mf.retryCount + 1; j++)
            {
                //if (j == 5)
                //{
                //    Messages.ShowAlertDialog("导出历史数据超时！", false);
                //    return;
                //}
                mf.SendCmd(Protocol.GetWriteDeviceCmd(0x10, sendbyte));
                Thread.Sleep(150);
                if (MainForm.isSuccess)
                {
                    return;
                }
              
            }
        }

        private void HisDataDownLoad_Load(object sender, EventArgs e)
        {
            //int intReportingCycle = Convert.ToUInt16(MainForm.rtuConfigInfo.ReportingCycle);//数据上传周期
            labTime.Text = dateStart.ToString("yyyy-MM-dd HH:mm:ss") + " - " + dateEnd.ToString("yyyy-MM-dd HH:mm:ss"); //dateEnd.AddMinutes(0- intReportingCycle).ToString("yyyy-MM-dd HH:mm:ss");
            Thread sub = new Thread(() =>
            {
                try
                {
                    for (int i = 1; i <= dataCount; i++)
                    {
                        MainForm.isSuccess = false;
                        DateTime dateTemp = dateStart.AddMinutes((i - 1) * intReportingCycle);
                        List<byte> listData = new List<byte>();
                        listData.Add(0x02);
                        listData.Add(MainForm.rtuConfigInfo.ReportingCycle);
                        listData.Add(Convert.ToByte(dateTemp.Year - 2000));
                        listData.Add(Convert.ToByte(dateTemp.Month));
                        listData.Add(Convert.ToByte(dateTemp.Day));
                        listData.Add(Convert.ToByte(dateTemp.Hour));
                        listData.Add(Convert.ToByte(dateTemp.Minute));
                        listData.Add(0x00);
                        SendHisData(listData.ToArray());

                        if (IsDisposed || !this.IsHandleCreated || this == null)
                        {
                            return;
                        }

                        this.BeginInvoke((MethodInvoker)delegate
                        {
                            progressBar.Value = Convert.ToInt16(Math.Round(i / (double)dataCount, 4, MidpointRounding.AwayFromZero) * 100);
                            labProgress.Text = progressBar.Value.ToString() + "%";
                            labProgress1.Text = i + "/" + dataCount;
                            if (progressBar.Value == 100)
                            {
                                mf.timer2.Enabled = true;
                            }
                        });


                        if (i == dataCount)
                        {
                            MessageBoxButtons messButton = MessageBoxButtons.OKCancel;
                            DialogResult dr = MessageBox.Show("历史数据导出完成，保存历史数据到Excel", "保存历史数据", messButton);
                            if (dr == DialogResult.OK)
                            {
                                FolderBrowserDialog fbd = new FolderBrowserDialog();
                                fbd.SelectedPath = @"C:\";
                                if (fbd.ShowDialog() == DialogResult.OK)
                                {
                                    if (fbd.SelectedPath != string.Empty)
                                    {
                                        string strNo = Protocol.ConvertData(MainForm.rtuConfigInfo.StationNo).Replace("\0", "");
                                        string strFullFileName = fbd.SelectedPath + "\\" + strNo + "_" + DateTime.Now.ToString("yyyyMMddHHmmss") + "_历史数据表.xlsx";
                                        string strTitle = "设备编号:" + strNo + "      开始时间:" + dateStart.ToString("yyyy-MM-dd HH:mm:ss") + "      结束时间:" + dateEnd.ToString("yyyy-MM-dd HH:mm:ss") + "      数据行数:" + mf.dtHisData.Rows.Count;
                                        ExcelManage.HisDataToExcelForXLSX(mf.dtHisData, strFullFileName, strTitle);
                                        Process m_Process = new Process();
                                        m_Process.StartInfo.FileName = strFullFileName;
                                        m_Process.Start();
                                    }
                                }
                            }
                            //mf.BindHisData();
                            //Messages.ShowAlertDialog("历史数据导出完成！", true);
                            return;
                        }
                    }
                }
                catch (Exception ex)
                {
                    Messages.SaveLogDialog("导出历史数据错误！", ex);
                }
            });
            sub.IsBackground = true;
            sub.SetApartmentState(ApartmentState.STA);
            sub.Start();
        }

        private void HisDataDownLoad_FormClosed(object sender, FormClosedEventArgs e)
        {
            mf.timer2.Enabled = true;
            this.Dispose();
        }
    }
}
